﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Kivensoft.XlsReader {
	class Utilities {
		private static readonly long DAY_MILLISECONDS = 24 * 60 * 60 * 1000;

		public static DateTime? ToDate(string excelDate, int baseYear) {
			try {
				DateTime convertedDate = new DateTime(baseYear, 1, 1);
				int MYSTERIOUS_CONSTANT = baseYear == 1900 ? 2 : 0;
				double daysToAdd = double.Parse(excelDate) - MYSTERIOUS_CONSTANT;
				convertedDate = convertedDate.AddDays(daysToAdd);
				return convertedDate;
			}
			catch (Exception) {
				return null;
			}
		}

		public static string ConvertDate(string excelDate, int baseYear) {
			DateTime? d = ToDate(excelDate, baseYear);
			return d == null ? null : d.Value.ToShortDateString();
		}

		public static TimeSpan? ToTime(string excelTime) {
			try {
				double time = double.Parse(excelTime, CultureInfo.GetCultureInfo("zh-CN"));
				double second = 1 / 86400d;
				double seconds = time / second;
				TimeSpan span = TimeSpan.FromSeconds(seconds);
				return span;
			}
			catch (Exception) {
				return null;
			}
		}

		public static string ConvertTime(string excelTime) {
			TimeSpan? t = ToTime(excelTime);
			return t == null ? null : t.Value.ToString();
		}

		public static DateTime? ToDateTime(string excelDateTime, int baseYear) {
			try {
				DateTime convertedDate = new DateTime(baseYear, 1, 1);
				int MYSTERIOUS_CONSTANT = baseYear == 1900 ? 2 : 0;
				double d = double.Parse(excelDateTime);
				int daysToAdd = (int)Math.Floor(d);
				convertedDate = convertedDate.AddDays(daysToAdd - MYSTERIOUS_CONSTANT);
				convertedDate = convertedDate.AddMilliseconds((int)((d - daysToAdd) * DAY_MILLISECONDS + 0.5));
				return convertedDate;
			}
			catch (Exception) {
				return null;
			}
		}

		public static string ConvertDateTime(string excelDateTime, int baseYear) {
			DateTime? d = ToDateTime(excelDateTime, baseYear);
			return d == null ? null : d.ToString();
		}
	}
}
